package com.kxsoft.gwt.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.kxsoft.gwt.client.GreetingService;
import com.kxsoft.gwt.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
    GreetingService {
  private Logger log = Logger.getLogger(GreetingServiceImpl.class);
  public String greetServer(String input) throws IllegalArgumentException {
    // Verify that the input is valid. 
    if (!FieldVerifier.isValidName(input)) {
      // If the input is not valid, throw an IllegalArgumentException back to
      // the client.
      throw new IllegalArgumentException(
          "Name must be at least 4 characters long");
    }
    String err="";
    Connection conn = null;
    String sql1 = "select max(m_id) from message";
    String dbURI = "//localhost:3306/myapp";
    String uStr = "root";
    String pStr = "HelloWorld1";
    try{
    	Class.forName("com.mysql.jdbc.Driver");
    	conn = DriverManager.getConnection("jdbc:mysql:"+dbURI+"?user="+uStr+"&password="+pStr+"&useUnicode=true&characterEncoding=utf-8");
    }catch(Exception e){
      	err = e.getMessage();
      	log.error(e);
    	e.printStackTrace();
    }
    if(conn!=null)
    	err = "database connection established";
    else
    {
      return err;
    }
    try{
    	Statement statement = conn.createStatement();
    	ResultSet rs1 = statement.executeQuery(sql1);
    	rs1.next();
    	int maxId = rs1.getInt(1);
    	maxId += 1;
    	Calendar c = Calendar.getInstance();
    	sql1 = "insert into message values(" + maxId + ",'" + input + "','" + c.getTime().toString() + "')";
    	Statement statement2 = conn.createStatement();
    	statement2.executeUpdate(sql1);
    	err += "<br><br>";
    	err += "message has been sent";
    	statement.close();
    	statement2.close();
    	conn.close();
    }catch(SQLException e)
    {
    	log.error(e);
    	err += "<br><br>";
    	err += e.getMessage();
    	err +="<br><br>";
    	err += sql1;
    }
    String serverInfo = getServletContext().getServerInfo();
    String userAgent = getThreadLocalRequest().getHeader("User-Agent");
    return "Hello, " + input + "!<br><br>I am running " + serverInfo
        + ".<br><br>It looks like you are using:<br>" + userAgent + ".<br><br>"
        + err;
  }
}
